<template>
  <div class="nav-search">
    <div class="search-input">
      <!--  @blur="isSearchNow = false" -->
      <el-input ref="inputRef" @blur="isSearchNow = false" @keyup.enter.native="toSearch" @focus="isSearchNow = true"
        placeholder="请输入搜索内容" v-model="input" clearable>
        <i slot="prefix" @click="toSearch" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <transition name="el-fade-in">
      <div v-show="isSearchNow" class="wrap-menu">
        <div class="search-menu">
          <!-- 历史搜索记录 -->
          <div v-show="input == '' " class="HotSearch">
            <div class="HistorySearch" v-show=" HistorySearch[0] !=  undefined">
              <div class="HistorySearch-title">
                <p>搜索历史<span class="el-icon-delete" @click="delteAll"></span></p>
                <p @click="isAll = true" v-show="isAll == false">查看全部</p>
              </div>
              <div class="HistorySearch-text" :class="{Alltext:isAll ==true }">
                <el-button v-for="(text,index6) of HistorySearch" :key="index6 +'-history'" class="TextBtn"
                  @click="searchbybtnText(text)" size="mini" round>{{text}}<span @click.stop="deleteText(index6)"
                    class="el-icon-close"></span></el-button>
              </div>
            </div>
            <!-- 热搜部分 -->
            <div class="HotSearchDetail">
              <div class="HotSearchDetail-title">
                <p>热搜榜</p>
              </div>
            </div>
            <div class="HotSearch-text">
              <div @click="searchbybtnText(item.searchWord)" v-for="(item,index0) of HotSearch" :key="index0 + '-hot'"
                class="HotSearch-detail-text">
                <div class="number" :class="{hotnumber: index0==0 || index0 == 1 ||index0 ==2}">{{index0+1}}</div>
                <div class="content-right">
                  <!-- 搜索关键词与热点 -->
                  <div class="content-top">
                    <div class="searchWord" :class="{searchWordHot:index0==0 || index0 == 1 ||index0 ==2}">
                      {{item.searchWord}}</div>
                    <img v-show="item.iconUrl" class="hotpic" :src="item.iconUrl" alt="">
                    <div class="score">{{item.score}}</div>
                  </div>
                  <!-- 当有内容介绍的时候显示 -->
                  <div v-show="item.content" class="content-bottom">
                    <div class="content">{{item.content}}</div>
                  </div>
                </div>

              </div>
            </div>
          </div>
          <!-- 搜索部分 -->
          <div v-show="input != '' && serachSuggestdetail.order != undefined" class="searchDetail">
            <div class="searchDetail-title">
              <i class="el-icon-search"></i>猜你想搜
            </div>
            <div class="searchDetail-title songs">
              <i class="el-icon-headset"></i>单曲
            </div>
            <div @click="searchbybtnText(song.name)" v-for="(song,index1) of serachSuggestdetail.songs"
              :key="index1+ '-song'" class="Searchcontent" v-html="heightlight(song.name)">

            </div>
            <div class="searchDetail-title artists">
              <i class="el-icon-user"></i>歌手
            </div>
            <div @click="searchbybtnText(artist.name)" v-for="(artist,index2) of serachSuggestdetail.artists"
              :key="index2 + '-artist'" class="Searchcontent">
              <div v-html="heightlight(artist.name)"></div>
            </div>
            <div class="searchDetail-title playlists">
              <i class="el-icon-s-unfold"></i>歌单
            </div>
            <div @click="searchbybtnText(playlist.name)" v-for="(playlist,index3) of serachSuggestdetail.playlists"
              :key="index3 + '-playlist'" class="Searchcontent" v-html="heightlight(playlist.name)">
            </div>
            <div class="searchDetail-title albums">
              <i class="el-icon-mic"></i>专辑
            </div>
            <div @click="searchbybtnText(album.name)" v-for="(album,index4) of serachSuggestdetail.albums"
              :key="index4+ '-album'" class="Searchcontent" v-html="heightlight(album.name)">

            </div>
          </div>
        </div>
      </div>

    </transition>
  </div>
</template>
<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { getsearchHotAPI, getsearchSuggestAPI } from "@/api/search";
// 本地存储历史记录
import { getItem, setItem } from "@/utils/stroage";
// 防抖
import { debounce } from "lodash";
const HistorySearchkey = "MUSIC-HISTORY-SEARCH";

export default {
  name: "search",
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      input: "",
      isSearchNow: false,
      // 历史搜索记录
      HistorySearch: getItem(HistorySearchkey) ? getItem(HistorySearchkey) : [],
      // 热搜榜
      HotSearch: [],
      // 查看全部历史记录
      isAll: false,
      serachSuggestdetail: {},
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    // 本地化存储搜索历史记录
    HistorySearch(newVal) {
      setItem(HistorySearchkey, newVal);
    },
    // 防抖函数
    input: {
      // 当searchText发生改变时调用handler函数
      // handler函数名称是固定的
      handler: debounce(function (value) {
        this.serachSuggest(value);
      }, 500),
      // 该回调将在监听开始后立刻调用
      immediate: true,
    },
  },
  //方法集合
  methods: {
    // 搜索关键字高亮事件
    heightlight(str) {
      const regStr = new RegExp(this.input, "gi");
      return str.replace(
        regStr,
        `<span style="color: #3296fa">${this.input}</span>`
      );
    },
    // 通过历史记录或者热搜进行搜索
    searchbybtnText(text) {
      this.input = text;
      // 添加历史事件
      this.toSearch();
    },
    // 回车触发搜索事件，保存历史记录，进行搜索
    toSearch() {
      if (this.input != "") {
        this.$refs.inputRef.blur((this.isSearchNow = false));
        // filter进行数组去重,然后在最前面添加，解决重复关键词的问题
        let newHistory = this.HistorySearch.filter(
          (text) => text !== this.input
        );
        newHistory.unshift(this.input);
        this.HistorySearch = newHistory;
        this.$router
          .push({
            path: "/search-detail",
            query: { text: this.input },
          })
          .catch((err) => err);
      }
    },
    // 删除历史记录
    deleteText(index) {
      this.HistorySearch.splice(index, 1);
    },
    // 清空历史记录
    delteAll() {
      this.HistorySearch = [];
    },
    // 热搜榜
    async getsearchHot() {
      const data = await getsearchHotAPI();
      if (data.data.code != 200) {
        console.log("热搜榜获取失败");
        return;
      }
      this.HotSearch = data.data.data;
    },
    // 搜索建议
    async serachSuggest(val) {
      if (val == "") {
        return;
      }
      const data = await getsearchSuggestAPI(val);

      console.log(data);
      this.serachSuggestdetail = data.data.result;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getsearchHot();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang='less'>
.nav-search {
  /deep/ .el-input__inner {
    border-radius: 50px;
    width: 250px;
  }
  .wrap-menu {
    position: absolute;
    margin-top: 5px;
    margin-left: -50px;
    z-index: 9999;
    width: 350px;
    height: 620px;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 0 5px rgb(194, 194, 194);
  }
  .search-menu {
    margin-top: 5px;
    width: 350px;
    height: 600px;
    overflow-x: hidden;
    overflow-y: auto;
    padding-bottom: 20px;
    .HistorySearch {
      margin-left: 20px;
      margin-right: 20px;
      cursor: default;
      .HistorySearch-title {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        p:first-of-type {
          font-size: 15px;
          color: rgb(90, 90, 90);
        }
        p:last-of-type {
          font-size: 15px;
          color: rgb(90, 90, 90);
          cursor: pointer;
        }
        p:last-of-type:hover {
          font-size: 15px;
          color: rgb(37, 37, 37);
          cursor: pointer;
        }
        .el-icon-delete {
          margin-left: 10px;
          cursor: pointer;
        }
      }
      .HistorySearch-text {
        margin-top: 5px;
        height: 70px;
        overflow: hidden;
        .TextBtn {
          margin-right: 5px;
          margin-top: 5px;
        }
        .el-icon-close {
          position: absolute;
          display: none;
        }
        .TextBtn:hover .el-icon-close {
          display: inline-block;
        }
      }
      .Alltext {
        height: 100%;
      }
    }
    .HotSearchDetail {
      margin-top: 10px;
      margin-left: 20px;
      margin-right: 20px;
      margin-bottom: 20px;

      .HotSearchDetail-title p {
        font-size: 15px;
        color: rgb(90, 90, 90);
        cursor: default;
      }
    }
    .HotSearch-text {
      cursor: default;
      .HotSearch-detail-text {
        display: flex;
        height: 55px;
        .number {
          line-height: 55px;
          width: 55px;
          text-align: center;
          flex-shrink: 0;
          color: rgb(209, 209, 209);
        }
        .hotnumber {
          color: #fd5656;
        }
        .content-right {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          .content-top {
            display: flex;
            width: 280px;
            align-items: center;
            .searchWord {
              flex-shrink: 0;
              font-size: 15px;
              color: #3d3d3d;
              margin-right: 5px;
            }
            .searchWordHot {
              font-weight: 900;
            }
            .score {
              flex-shrink: 0;
              font-size: 12px;
              color: #cfcfcf;
              margin-left: 5px;
            }
            .hotpic {
              flex-shrink: 0;
              width: 20px;
              height: 10px;
            }
          }
          .content-bottom {
            .content {
              width: 280px;
              font-size: 14px;
              color: #8a8a8a;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }
        }
      }
      .HotSearch-detail-text:hover {
        background-color: rgb(223, 223, 223);
      }
    }
  }
  //搜索建议
  .searchDetail {
    display: flex;
    width: 350px;
    flex-wrap: wrap;
    cursor: default;
    .searchDetail-title {
      flex-shrink: 0;
      width: 350px;
      height: 30px;
      font-size: 15px;
      line-height: 30px;
      color: #838383;
      i {
        padding-right: 10px;
        padding-left: 10px;
      }
    }
    .Searchcontent {
      flex-shrink: 0;
      width: 350px;
      height: 30px;
      font-size: 15px;
      line-height: 30px;
      color: #3d3d3d;
      padding-left: 35px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .Searchcontent:hover {
      background-color: #e2e2e2;
    }
  }
}
::-webkit-scrollbar {
  width: 5px;
}
::-webkit-scrollbar-thumb {
  background-color: lightsteelblue;
  border-radius: 5px;
}
::-webkit-scrollbar-track {
  background-color: transparent;
}
</style>